%computes the level of debt at entry and value added that solves the FE and FC conditions
function yy=fun_EntryEq(vars,pars)

global cub_spl_v cub_spl_x pp_star Amin

q_hig=pars(1);
zlow=pars(2);
q_low=pars(3);
zhig=pars(4);
q_mid=pars(5);
zmid=pars(6);
k=pars(7);
varzeta=pars(8);
rbar=pars(9);
tau=pars(10);
r=pars(11);
z_0=pars(12);
delta=pars(13);
xi=pars(14);
R0=pars(15);

chi=pars(16);
coupon=pars(17);
rho=pars(18);
sigma=pars(19);
phi=pars(20);
a=pars(21);
varphi=pars(22);
nu=pars(23);
markupsub=pars(24);
A0=pars(34);

incid =pars(end-1);
k_nosub=pars(end);

B0=max(0,vars(1));
A=min(vars(2),A0);
B00=max(0,vars(3));
b_common  = B0/(z_0*A);
b_common0 = B00/(z_0*A);

blow=b_common/zhig;
bmid=b_common/zmid;
bhig=b_common/zlow;
x0_hig = fnval(cub_spl_x,[max(0,bhig);max(A,Amin)]);
x0_low = fnval(cub_spl_x,[max(0,blow);max(A,Amin)]);
x0_mid = fnval(cub_spl_x,[max(0,bmid);max(A,Amin)]);
v0_hig = fnval(cub_spl_v,[max(0,bhig);max(A,Amin)]);
v0_low = fnval(cub_spl_v,[max(0,blow);max(A,Amin)]);
v0_mid = fnval(cub_spl_v,[max(0,bmid);max(A,Amin)]);
if tau>0 &&  bhig>ppval(pp_star,max(A,Amin))
    bhig   = fun_buyback(bhig,max(A,Amin),tau/(z_0*A),cub_spl_v,cub_spl_x);
    x0_hig = fnval(cub_spl_x,[max(0,bhig);max(A,Amin)]);
    v0_hig = fnval(cub_spl_v,[max(0,bhig);max(A,Amin)]) -  x0_hig.*(b_common/zlow-bhig);
end
blow=b_common0/zhig;
bmid=b_common0/zmid;
bhig=b_common0/zlow;
x00_hig = fnval(cub_spl_x,[max(0,bhig);max(A,Amin)]);
x00_low = fnval(cub_spl_x,[max(0,blow);max(A,Amin)]);
x00_mid = fnval(cub_spl_x,[max(0,bmid);max(A,Amin)]);
v00_hig = fnval(cub_spl_v,[max(0,bhig);max(A,Amin)]);
v00_low = fnval(cub_spl_v,[max(0,blow);max(A,Amin)]);
v00_mid = fnval(cub_spl_v,[max(0,bmid);max(A,Amin)]);

Ev0    = z_0*A*(zlow*v0_hig*q_hig+zhig*v0_low*q_low+zmid*v0_mid*q_mid);
Ex0    =       min(1,(x0_hig*q_hig+x0_low*q_low+x0_mid*q_mid));

Ev00    = z_0*A*(zlow*v00_hig*q_hig+zhig*v00_low*q_low+zmid*v00_mid*q_mid);
Ex00    =       min(1,(x00_hig*q_hig+x00_low*q_low+x00_mid*q_mid));
if k>varzeta/(r+xi) && incid ==1
    yy(1)= k-varzeta/(r+xi)- B0*Ex0;
    yy(2)= -(Ev0+tau)+varzeta/(r+xi);
    yy(3)= B0-B00;
elseif k>varzeta/(r+xi) && incid <1
    Ex = (Ex0*incid*B0+Ex00*(1-incid)*B00)/(incid*B0+(1-incid)*B00);
    yy(1)= k-varzeta/(r+xi)- B0*Ex;
    yy(2)= -(Ev0+tau)*incid - Ev00*(1-incid) +varzeta/(r+xi);
    yy(3)= k_nosub-varzeta/(r+xi)- B00*Ex;
elseif k<=varzeta/(r+xi) && incid <1
    yy(1)= B0;
    yy(2)= k-(Ev0+tau);
    yy(3)= k_nosub-varzeta/(r+xi)- B00*Ex00;
else
    yy(1)= B0;
    yy(2)= -(Ev0+tau)+k;
    yy(3)= B00;
end


